//
//  TableViewController.swift
//  FaceBook
//
//  Created by 劢克科技 on 2019/2/1.
//  Copyright © 2019 劢克科技. All rights reserved.
//

import UIKit

@objcMembers
class Post: SafeObject {
    var username: String?
    var statusText: String?
    var statusImage: String?
}

class SafeObject: NSObject {
    /// 过滤json中多余的字段，防止报错
    override func setValue(_ value: Any?, forKey key: String) {
        let selectorString = "set\(key.uppercased().first!)\(key.dropFirst()):"
        let selector = Selector(selectorString)
        if responds(to: selector) {
            super.setValue(value, forKey: key)
        }
    }
}

let CellId = "Cell"
var posts = [Post]()

class TableViewController: UITableViewController {
    
    lazy var blackBgCover: UIView = {
        let cover = UIView()
        cover.frame = view.superview?.frame ?? CGRect.zero
        cover.backgroundColor = UIColor.black
        return cover
    }()
    
    lazy var zoomImageView = UIImageView()
    lazy var startFrame = CGRect.zero
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(TableCell.self, forCellReuseIdentifier: CellId)
        tableView.tableFooterView = UIView()
        tableView.allowsSelection = false
        tableView.estimatedRowHeight = 350
        
        jsonData()
        setUI()
    }
    
    private func setUI() {
        navigationItem.title = "Face book"
    }
    
    private func jsonData() {
        guard let path = Bundle.main.path(forResource: "sample", ofType: "json") else { return }
        do {
            let data = try NSData(contentsOfFile: path, options: .mappedIfSafe)
            let jsonDict = try JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers)
            guard let postDict = jsonDict as? [String: Any] else { return }
            for single in postDict["post"] as! [[String: Any]] {
                let post = Post()
                post.setValuesForKeys(single)
                posts.append(post)
            }
        } catch let err {
            print(err)
        }
    }
}

//MARK: - DataSource
extension TableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CellId) as! TableCell
        cell.post = posts[indexPath.row]
        cell.delegate = self
        return  cell
    }
}

extension TableViewController: TableCellDelegate {
    func animate(statusImageView: UIImageView) {
        guard let startFrame = statusImageView.superview?.convert(statusImageView.frame, to: nil) else {
            return
        }
        self.startFrame = startFrame
        guard let imageOriginSize = statusImageView.image?.size else { return }
        let zoomHeight = UIScreen.main.bounds.width * imageOriginSize.height / imageOriginSize.width
        zoomImageView = UIImageView()
        zoomImageView.clipsToBounds = true
        zoomImageView.frame = startFrame
        zoomImageView.isUserInteractionEnabled = true
        zoomImageView.image = statusImageView.image
        zoomImageView.contentMode = .scaleAspectFill
        zoomImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(animateOut)))
        
        blackBgCover.alpha = 0
        view.superview?.addSubview(blackBgCover)
        view.superview?.addSubview(zoomImageView)
        
        UIView.animate(withDuration: 0.5) {
            let screenW = UIScreen.main.bounds.width
            let screenH = UIScreen.main.bounds.height
            let y = (screenH - zoomHeight) / 2
            self.zoomImageView.frame = CGRect(x: 0, y: y, width: screenW, height: zoomHeight)
            self.blackBgCover.alpha = 1
            self.navigationController?.navigationBar.isHidden = true
            self.tabBarController?.tabBar.isHidden = true
        }
    }
    
    @objc func animateOut() {
        self.navigationController?.navigationBar.isHidden = false
        self.tabBarController?.tabBar.isHidden = false
        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
            self.blackBgCover.alpha = 0
            self.zoomImageView.frame = self.startFrame
        }) { (_) in
            self.blackBgCover.removeFromSuperview()
            self.zoomImageView.removeFromSuperview()
        }
    }
}

protocol TableCellDelegate {
    func animate(statusImageView: UIImageView)
}

class TableCell: UITableViewCell {
    
    var delegate: TableCellDelegate?
    
    var post: Post? {
        didSet {
            if let usernameText = post?.username {
                let attributeText = NSMutableAttributedString(string: usernameText, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)])
                attributeText.append(NSAttributedString(string: "\ntime: 2019-01-20 start: 99 views: 99 ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]))
                
                let attachment = NSTextAttachment()
                attachment.image = #imageLiteral(resourceName: "logo")
                attachment.bounds = CGRect(x: 0, y: -2, width: 15, height: 15)
                attributeText.append(NSAttributedString(attachment: attachment))
                
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.lineSpacing = 4
                attributeText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributeText.length))
                
                username.attributedText = attributeText
            }
            
            if let statusText = post?.statusText {
                contentText.text = statusText
            }
            
            if let image = post?.statusImage {
                statusImage.image = UIImage(named: image)
//                let imageH = UIScreen.main.bounds.width / image.size.width * image.size.height
//                for item in statusImage.constraints {
//                    item.constant = imageH
//                }
            }
        }
    }
    
    lazy var avatar: UIImageView = {
        let imageV = UIImageView()
        imageV.image = #imageLiteral(resourceName: "1")
        imageV.translatesAutoresizingMaskIntoConstraints = false
        return imageV
    }()
    
    lazy var username: UILabel = {
        let label = UILabel()
        label.numberOfLines = 2
        
        let attributeText = NSMutableAttributedString(string: "Let us do that app!", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)])
        attributeText.append(NSAttributedString(string: "\ntime: 2019-01-20 start: 99 views: 99 ", attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]))
        
        let attachment = NSTextAttachment()
        attachment.image = #imageLiteral(resourceName: "logo")
        attachment.bounds = CGRect(x: 0, y: -2, width: 15, height: 15)
        attributeText.append(NSAttributedString(attachment: attachment))
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 4
        attributeText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributeText.length))
        
        label.attributedText = attributeText
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    lazy var contentText: UILabel = {
        let label = UILabel()
        label.text = "Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!Let us do that app!"
        label.font = UIFont.systemFont(ofSize: 14)
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    lazy var statusImage: UIImageView = {
        let imageV = UIImageView(image: #imageLiteral(resourceName: "2"))
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        imageV.translatesAutoresizingMaskIntoConstraints = false
        imageV.isUserInteractionEnabled = true
        imageV.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(animate)))
        return imageV
    }()
    
    @objc func animate() {
        delegate?.animate(statusImageView: statusImage)
    }
    
    lazy var likeComments: UILabel = {
        let label = UILabel()
        label.text = "400 Likes  123 Comments"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = rgb(red: 149, green: 153, blue: 166, alpha: 1)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    lazy var like = self.titleImageButton(title: "Like", image: #imageLiteral(resourceName: "weibiaoti1"))
    lazy var comment = self.titleImageButton(title: "Comment", image: #imageLiteral(resourceName: "comment"))
    lazy var share = self.titleImageButton(title: "Share", image: #imageLiteral(resourceName: "share"))
    
    func rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
        return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha)
    }
    
    func titleImageButton(title: String, image: UIImage) -> UIButton {
        let btn = UIButton()
        btn.setTitle(title, for: .normal)
        btn.setImage(image, for: .normal)
        btn.translatesAutoresizingMaskIntoConstraints = false
        btn.setTitleColor(#colorLiteral(red: 0.5411153436, green: 0.5412116647, blue: 0.5411092043, alpha: 1), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        return btn
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: CellId)
        
        contentView.addSubview(avatar)
        contentView.addSubview(username)
        contentView.addSubview(contentText)
        contentView.addSubview(statusImage)
        contentView.addSubview(likeComments)
        contentView.addSubview(like)
        contentView.addSubview(comment)
        contentView.addSubview(share)
        
        setUpLayout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpLayout() {
        avatar.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8).isActive = true
        avatar.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
        avatar.widthAnchor.constraint(equalToConstant: 50).isActive = true
        avatar.heightAnchor.constraint(equalToConstant: 50).isActive = true
        
        username.leftAnchor.constraint(equalTo: avatar.rightAnchor, constant: 8).isActive = true
        username.topAnchor.constraint(equalTo: avatar.topAnchor).isActive = true
        
        contentText.topAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 4).isActive = true
        contentText.heightAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true
        contentText.leftAnchor.constraint(equalTo: avatar.leftAnchor).isActive = true
        contentText.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
        
        statusImage.topAnchor.constraint(equalTo: contentText.bottomAnchor, constant: 4).isActive = true
        statusImage.leftAnchor.constraint(equalTo: avatar.leftAnchor).isActive = true
        statusImage.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
        statusImage.heightAnchor.constraint(equalToConstant: 200).isActive = true
        
        likeComments.topAnchor.constraint(equalTo: statusImage.bottomAnchor, constant: 4).isActive = true
        likeComments.leftAnchor.constraint(equalTo: avatar.leftAnchor).isActive = true
        likeComments.heightAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true
        
        like.topAnchor.constraint(equalTo: likeComments.bottomAnchor, constant: 10).isActive = true
        like.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4).isActive = true
        like.heightAnchor.constraint(equalToConstant: 24).isActive = true
        like.leftAnchor.constraint(equalTo: likeComments.leftAnchor).isActive = true
        like.widthAnchor.constraint(equalTo: comment.widthAnchor).isActive = true
        
        comment.topAnchor.constraint(equalTo: like.topAnchor).isActive = true
        comment.leftAnchor.constraint(equalTo: like.rightAnchor, constant: 5).isActive = true
        comment.widthAnchor.constraint(equalTo: share.widthAnchor).isActive = true
        comment.heightAnchor.constraint(equalTo: like.heightAnchor).isActive = true
    
        share.topAnchor.constraint(equalTo: like.topAnchor).isActive = true
        share.leftAnchor.constraint(equalTo: comment.rightAnchor, constant: 5).isActive = true
        share.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
        share.heightAnchor.constraint(equalTo: like.heightAnchor).isActive = true
    }
}


